﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace 自动校园网登陆
{
    internal class Util
    {
        private static string get_info_api = "http://172.16.8.8/cgi-bin/rad_user_info?callback=jQuery112406118340540763985_1556004912581&_=1556004912582";

        [DllImport("kernel32")]
        private static extern int GetPrivateProfileString(string lpAppName, string lpKeyName, string lpDefault, StringBuilder lpReturnedString, int nSize, string lpFileName);

        [DllImport("kernel32")]
        private static extern int WritePrivateProfileString(string lpApplicationName, string lpKeyName, string lpString, string lpFileName);

        /// <summary>
        /// 读取INI文件值
        /// </summary>
        /// <param name="section">节点名</param>
        /// <param name="key">键</param>
        /// <param name="def">未取到值时返回的默认值</param>
        /// <param name="filePath">INI文件完整路径</param>
        /// <returns>读取的值</returns>
        public static string Read(string section, string key, string def, string filePath)
        {
            StringBuilder sb = new StringBuilder(1024);
            GetPrivateProfileString(section, key, def, sb, 1024, filePath);
            return sb.ToString();
        }

        /// <summary>
        /// 写INI文件值
        /// </summary>
        /// <param name="section">欲在其中写入的节点名称</param>
        /// <param name="key">欲设置的项名</param>
        /// <param name="value">要写入的新字符串</param>
        /// <param name="filePath">INI文件完整路径</param>
        /// <returns>非零表示成功，零表示失败</returns>
        public static int Write(string section, string key, string value, string filePath)
        {
            return WritePrivateProfileString(section, key, value, filePath);
        }

        /// <summary>
        /// 删除节
        /// </summary>
        /// <param name="section">节点名</param>
        /// <param name="filePath">INI文件完整路径</param>
        /// <returns>非零表示成功，零表示失败</returns>
        public static int DeleteSection(string section, string filePath)
        {
            return Write(section, null, null, filePath);
        }

        /// <summary>
        /// 删除键的值
        /// </summary>
        /// <param name="section">节点名</param>
        /// <param name="key">键名</param>
        /// <param name="filePath">INI文件完整路径</param>
        /// <returns>非零表示成功，零表示失败</returns>
        public static int DeleteKey(string section, string key, string filePath)
        {
            return Write(section, key, null, filePath);
        }

        public static bool IsConnectedToInternet()
        {
            string host = "www.baidu.com";
            bool result = false;
            Ping p = new Ping();
            try
            {
                PingReply reply = p.Send(host, 350);
                if (reply.Status == IPStatus.Success)
                    return true;
            }
            catch (Exception)
            {

            }
            return result;
        }

        public static bool IsJxnuWLAN()
        {
            ProcessStartInfo info = new ProcessStartInfo("netsh", "wlan show interfaces");
            info.WorkingDirectory = @"c:\windows\system32";
            info.WindowStyle = ProcessWindowStyle.Hidden;
            info.CreateNoWindow = true;
            info.RedirectStandardOutput = true;
            info.UseShellExecute = false;
            Process proc = new Process();
            proc.StartInfo = info;
            proc.Start();
            string s = proc.StandardOutput.ReadToEnd().ToLower();
            proc.Close();
            if (s.Contains("jxnu_stu"))
                return true;
            return false;
        }

        public static string GetResponseText(string url, Dictionary<string, string> param)
        {
            if (param != null && param.Count > 0)
            {
                url += "?";
                foreach (KeyValuePair<string, string> kvp in param)
                {
                    url += WebUtility.UrlEncode(kvp.Key) + "=" + WebUtility.UrlEncode(kvp.Value) + "&";
                }
                url = url.Substring(0, url.Length - 1);
            }

            HttpWebResponse response = CreateGetHttpResponse(url);
            if (response == null)
                return "offline_error";
            //获取流
            Stream streamResponse = response.GetResponseStream();
            //使用UTF8解码
            StreamReader streanReader = new StreamReader(streamResponse, Encoding.UTF8);

            string retString = streanReader.ReadToEnd();

            return retString;
        }

        public static string GetNetworkStatusCode()
        {
            string info_response = Util.GetResponseText(get_info_api, null);
            Regex r = new Regex("\"error\":\"(.*?)\"");
            string error_code = r.Match(info_response).Groups[1].Value;
            return error_code;
        }

        public static HttpWebResponse CreateGetHttpResponse(string url)
        {
            HttpWebResponse response = null;
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.ContentType = "text/html;chartset=UTF-8";
                request.UserAgent = "Mozilla / 5.0(Windows NT 10.0; Win64; x64; rv: 48.0) Gecko / 20100101 Firefox / 48.0"; //火狐用户代理
                request.Method = "GET";
                response = (HttpWebResponse)request.GetResponse();
            }
            catch(WebException)
            {

            }

            return response;
        }

        public static string GetIPAddress()
        {
            string URL = "http://172.16.8.8";
            string response = GetResponseText(URL, null);
            Regex r = new Regex("id=\"user_ip\" value=\"(.*?)\"");
            string ip = r.Match(response).Groups[1].Value;
            return ip;
        }

        public static string HmacMD5(string source, string key)
        {
            HMACMD5 hmaCmd = new HMACMD5(Encoding.Default.GetBytes(key));
            byte[] byteArray = hmaCmd.ComputeHash(Encoding.Default.GetBytes(source));
            StringBuilder sb = new StringBuilder();

            for (int i = 0; i < byteArray.Length; i++)
            {
                sb.Append(byteArray[i].ToString("x2"));
            }
            hmaCmd.Clear();
            return sb.ToString();
        }

        public static long GetTotalSeconds(bool isMillisecond = true)
        {
            var ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            var timeStamp = isMillisecond ? Convert.ToInt64(ts.TotalMilliseconds) : Convert.ToInt64(ts.TotalSeconds);
            return timeStamp;
        }

        public static string GetSHA1(string pwd)
        {
            //创建SHA1加密算法对象
            SHA1 sha1 = SHA1.Create();
            //将原始密码转换为字节数组
            byte[] originalPwd = Encoding.UTF8.GetBytes(pwd);
            //执行加密
            byte[] encryPwd = sha1.ComputeHash(originalPwd);
            //将加密后的字节数组转换为大写字符串
            return string.Join("", encryPwd.Select(b => string.Format("{0:x2}",
           b)).ToArray()).ToLower();
        }
    }
}
